What is xml-name-validator?
The xml-name-validator npm package is used to check if a string is a valid XML name, according to the XML specification. It can validate both XML names and qualified names (QNames), which are used in XML documents to ensure that element and attribute names are compliant with the XML naming rules.
What are xml-name-validator's main functionalities?
Validating XML names
This feature allows you to validate whether a given string is a valid XML name. The `isName` function returns `true` if the string is a valid XML name, and `false` otherwise.
const { isName, isQName } = require('xml-name-validator');
const validName = 'validElement';
const invalidName = '1InvalidElement';
console.log(isName(validName)); // true
console.log(isName(invalidName)); // false
Validating XML qualified names (QNames)
This feature allows you to validate whether a given string is a valid XML qualified name (QName). The `isQName` function returns `true` if the string is a valid QName, which includes a namespace prefix, and `false` otherwise.
const { isName, isQName } = require('xml-name-validator');
const validQName = 'ns:validElement';
const invalidQName = 'ns:1InvalidElement';
console.log(isQName(validQName)); // true
console.log(isQName(invalidQName)); // false
Other packages similar to xml-name-validator
libxmljs
libxmljs is a Node.js package that provides bindings to the libxml C library. It allows for parsing and serializing XML and includes capabilities for validating XML names as part of its broader feature set. Compared to xml-name-validator, libxmljs is a more comprehensive library for working with XML, but it is also more complex and has a larger footprint.
xmldom
xmldom is a pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module. It provides a way to parse XML strings and serialize DOM trees back to XML. While it does not have a dedicated method for validating XML names, it inherently checks for valid names during parsing. xmldom offers a broader range of XML manipulation features compared to xml-name-validator, which focuses solely on name validation.
Validate XML Names and Qualified Names
This package simply tells you whether or not a string matches the Name
or QName
productions in the XML Namespaces specification. We use it for implementing the validate algorithm in jsdom, but you can use it for whatever you want.
Usage
This package's main module exports two functions, name()
and qname()
. Both take a string and return a boolean indicating whether or not the string matches the relevant production.
"use strict":
const xnv = require("xml-name-validator");
xnv.name("x");
xnv.name(":");
xnv.name("a:0");
xnv.name("a:b:c");
xnv.name("\\");
xnv.name("'");
xnv.name("0");
xnv.name("a!");
xnv.qname("x");
xnv.qname("a0");
xnv.qname("a:b");
xnv.qname(":a");
xnv.qname(":b");
xnv.qname("a:b:c");
xnv.qname("a:0");